// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db=cloud.database();
const MAX_LIMIT = 100; //服务端limit的上限

// 云函数入口函数
exports.main = async (event, context) => {

  let orderDate=event.orderDate; //查询日期
  let orders=[]; //定义最终返回的订单集合
  let condition = {
    orderDate: orderDate
  } //查询条件
  // 先取出集合记录总数
  let countResult = await db.collection('orders').where(condition).count()
  let total = countResult.total
  // 计算需分几次取
  let batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  let tasks = []
  for (let i = 0; i < batchTimes; i++) {
    let promise = db.collection('orders').skip(i * MAX_LIMIT).limit(MAX_LIMIT)
      .where(condition) //条件：用户id，当前状态，当日日期
      .field({
        orderId: true,
        simpleId: true,
        orderTypeName: true,
        orderDate: true,
        orderTime: true,
        totalCount: true,
        totalCost: true,
        status: true,
      })
      .orderBy('oneDayId', 'asc') //按照下单流水号降序排列
      .get()
    tasks.push(promise)
  }
  if (batchTimes == 0) {
    //如果没有满足条件的记录
    orders=[];
  } else {
    // 等待所有
    let allPromise = await (async function (promises) {
      return (await Promise.all(tasks)).reduce((acc, cur) => {
        return {
          data: acc.data.concat(cur.data),
          errMsg: acc.errMsg,
        }
      })
    })(tasks)
    //将此状态下的所有订单，放入orders中
    orders = allPromise.data
  }
  return orders; //返回查询到的所有当日订单
}